<template>
  <div class="work">
    <el-container>
      <el-header>加班申请</el-header>
      <el-main>
        <div class="nav">
          <el-button type="warning" @click="showDialog">发起新的</el-button>
          <el-upload
            action="/api/work/import"
            :headers="headers"
            name="excel"
            :data="{ userid: formData.userid }"
            :on-change="onChange"
            :on-success="onSuccess"
            :on-error="onError"
            :show-file-list="false"
            :disabled="uploading"
            accept=".xlsx;.slx"
          >
            <el-button :loading="uploading">导入</el-button>
          </el-upload>

          <el-button>
            <el-link
              :href="'/api/work/download?userid=' + formData.userid"
              target="_blank"
              >导出</el-link
            >
          </el-button>
          <el-tabs
            v-model="activeName"
            class="demo-tabs"
            @tab-click="handleClick"
          >
            <el-tab-pane label="待办事项" name="1"></el-tab-pane>
            <el-tab-pane label="已办事项" name="2"></el-tab-pane>
            <el-tab-pane label="抄送事项" name="3"></el-tab-pane>
            <el-tab-pane label="我发起的" name="4"></el-tab-pane>
            <el-tab-pane label="全部数据" name="5"></el-tab-pane>
            <el-tab-pane label="概览" name="6"></el-tab-pane>
            <el-tab-pane label="统计报表" name="7"></el-tab-pane>
          </el-tabs>
        </div>
      </el-main>
      <!-- 表格 -->
      <el-table
        :data="tableData"
        style="width: 100% font-size:14px"
        size="small"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="编号" prop="_id" show-overflow-tooltip />
        <el-table-column
          label="当前流程"
          prop="status"
          :formatter="formatterStatus"
        />
        <el-table-column label="申请人" prop="name" />
        <el-table-column label="加班类型" prop="type" />
        <el-table-column label="事由说明" prop="reason" show-overflow-tooltip />
        <el-table-column
          label="开始时间"
          :formatter="formatterTime"
          prop="starttime"
        />
        <el-table-column
          label="结束时间"
          :formatter="formatterTime"
          prop="endtime"
        />
        <el-table-column label="加班时长" prop="hours" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click.prevent="editRow(scope)"
            >
              编辑
            </el-button>
            <el-button
              link
              type="primary"
              size="small"
              @click.prevent="deleteRow(scope)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        class="page"
      />
      <!-- 抽屉组件 -->
      <el-drawer
        ref="drawerRef"
        v-model="addDialog"
        title="加班申请"
        direction="rtl"
        custom-class="demo-drawer"
      >
        <div class="demo-drawer__content">
          <!-- 新增表单 -->
          <el-form
            :model="formData"
            label-position="top"
            :rules="rules"
            ref="formRef"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="申请人" prop="name">
                  <el-input v-model="formData.name" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所在部门">
                  <el-input v-model="formData.dept" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="加班类型">
                  <el-select v-model="formData.checktype" placeholder="请选择">
                    <el-option label="工作日几班" value="0" />
                    <el-option label="周末加班" value="1" />
                    <el-option label="节假日加班" value="2" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="事由说明" prop="reason">
                  <el-input
                    type="textarea"
                    v-model="formData.reason"
                    placeholder="输入内容"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="开始日期" prop="starttime">
                  <div class="block">
                    <span class="demonstration"></span>
                    <el-date-picker
                      v-model="formData.starttime"
                      type="datetime"
                      placeholder="请选择结束日期"
                      :default-time="defaultTime"
                    />
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="结束日期" prop="endtime">
                  <div class="block">
                    <span class="demonstration"></span>
                    <el-date-picker
                      v-model="formData.endtime"
                      type="datetime"
                      placeholder="选择结束日期"
                      :default-time="defaultTime"
                    />
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="加班时长" prop="days" :required="true">
                  <el-input v-model="formData.hours" disabled />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <div class="demo-drawer__footer">
            <el-button @click="addDialog = false">取消</el-button>
            <el-button type="primary" @click="onSubmit(formRef)"
              >提交申请</el-button
            >
          </div>
        </div>
      </el-drawer>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import { work_add, work_list, work_delete } from "../../api/index";
import { ElNotification } from 'element-plus'

var activeName = reactive("");
var tableData = ref([]);
var total = ref(0);
var addDialog = ref(false);
var uploading = ref(false);
var formData = ref({
  userid: JSON.parse(localStorage.getItem("userinfo"))._id,
  name: JSON.parse(localStorage.getItem("userinfo")).name,
  reason: "",
  starttime: "",
  endtime: "",
  hours: "",
});
var headers = ref({
  Authorization: "Bearer" + " " + localStorage.getItem("token"),
});

var ruleFormRef = ref();
var formRef = ref();
//组件挂在完成时,请求出差申请列表
onMounted(async () => {
  var userinfo = JSON.parse(localStorage.getItem("userinfo"));
  var res = await work_list({ userid: userinfo._id, page: 1 });
  console.log(res.data.list);
  tableData.value = res.data.list;
  total.value = res.data.total;
});

var handleClick = (name) => {
  // console.log(activeName.value, name);
};
//发起新的请假申请
var showDialog = () => {
  addDialog.value = true; //弹出抽屉
  formRef.value.resetFields(); //重置表单
  formData.value = {
    userid: JSON.parse(localStorage.getItem("userinfo"))._id,
    name: JSON.parse(localStorage.getItem("userinfo")).name,
    reason: "",
    starttime: "",
    endtime: "",
    hours: "",
  };
};

//验证请假事由
const validateReason = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("内容不能为空"));
  } else {
    callback();
  }
};

//验证开始日期
const validateStarttime = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请选择日期"));
  } else {
    if (new Date(formData.value.starttime) > new Date(formData.value.endtime)) {
      formData.value.starttime = "";
      formData.value.hours = "";
      callback(new Error("出发日期必须小于返回日期"));
    } else {
      //验证通过后计算天数
      formData.value.days =
        (new Date(formData.value.endtime) -
          new Date(formData.value.starttime)) /
        (24 * 60 * 60 * 1000);
    }
    callback();
  }
};
//验证返回日期
const validateEndtime = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请选择返回日期"));
  } else {
    if (new Date(formData.value.starttime) > new Date(formData.value.endtime)) {
      console.log(formData.value.starttime, formData.value.endtime);
      formData.value.endtime = "";
      formData.value.hours = "";
      callback(new Error("返回日期必须大于出发日期"));
    } else {
      //验证通过后计算天数
      formData.value.hours =
        (new Date(formData.value.endtime) -
          new Date(formData.value.starttime)) /
        (60 * 60 * 1000);
    }
    callback();
  }
};

//验证表单项的验证规则
const rules = reactive({
  reason: [{ validator: validateReason, trigger: "blur", required: true }],
  starttime: [
    { validator: validateStarttime, trigger: "change", required: true },
  ],
  endtime: [{ validator: validateEndtime, trigger: "change", required: true }],
});

//提交申请
var onSubmit = (formRef) => {
  formRef.validate(async (valid) => {
    if (valid) {
      if (formData.value._id) {
        delete formData.value._id;
        var res = await work_add(formData.value);
        if (res.data.code == 200) {
          ElNotification({
            //弹出通知
            title: "新增通知",
            message: res.data.msg,
            type: "success",
          });
        }
        addDialog.value = false; //关闭抽屉
        tableData.value = res.data.list;
        total.value = res.data.total;
        console.log(total.value);
        formRef.resetFields(); //重置表单
        var userinfo = JSON.parse(localStorage.getItem("userinfo"));
      } else {
        var res = await work_add(formData.value);
        if (res.data.code == 200) {
          ElMessage({
            message: "新增成功",
            type: "success",
          });
        addDialog.value = false; //关闭抽屉
        tableData.value = res.data.list;
        total.value = res.data.total;
        console.log(total.value);
        formRef.resetFields(); //重置表单
        }
        else {
          ElNotification({
            title: "新增通知",
            message: res.data.msg,
            type: "error",
          });
        }
      }
    } else {
      console.log("error submit!");
      return false;
    }
  });
};

//格式化流程状态
var formatterStatus = function (row, column, cellValue, index) {
  return cellValue == 0 ? "审核中" : "已通过";
};

//补零
var addZero = (num) => {
  return num < 10 ? "0" + num : num;
};
//格式化时间
var formatterTime = function (row, column, cellValue, index) {
  var d = new Date(cellValue);
  return `${d.getFullYear()}-${addZero(d.getMonth() + 1)}-${addZero(
    d.getDate()
  )}`;
};

//删除
var deleteRow = async (scope) => {
  var userinfo = JSON.parse(localStorage.getItem("userinfo"));
  var res = await work_delete({
    userid: userinfo._id,
    id: scope.row._id,
    page: 1,
  });
  if (res.data.code == 200) {
    ElMessage({
      message: "刪除成功",
      type: "success",
    });
  }
  tableData.value = res.data.list;
  total.value = res.data.total;
};

//編輯
var editRow = (scope) => {
  addDialog.value = true; //彈出抽屜
  formData.value = JSON.parse(JSON.stringify(scope.row));
};

//文件上传成功的回调
var onSuccess = (response, uploadFile, uploadFiles) => {
  uploading.value = false; //影藏loading
  if (response.code == 200) {
    ElMessage({
      message: "上传成功",
      type: "success",
    });
  }
};

//文件上传失败的回调
var onError = (error, uploadFile, uploadFiles) => {
  uploading.value = false; //隐藏loading
  if (error) {
    ElMessage({
      message: "上传失败",
      type: "error",
    });
  }
};

//分页
var handlepage = async (page) => {
  var userinfo = JSON.parse(localStorage.getItem("userinfo"));
  var res = await work_list({ userid: userinfo._id, page });
  tableData.value = res.data.list;
};
</script>

<style scoped lang="scss">
.el-main,
.el-header {
  margin: 5px;
  padding: 0;
}
.el-header {
  font-size: 14px;
  line-height: 30px;
  font-weight: bolder;
  height: 40px;
  border-bottom: 1px solid rgb(231, 229, 229);
}
.el-main {
  .el-tabs {
    height: 32px;
    margin-left: 30px;
    border: 0;
  }
  .nav {
    display: flex;
    border-bottom: 1px solid rgb(231, 229, 229);
    box-sizing: border-box;
    padding-bottom: 5px;
  }
  .el-tabs__nav-wrap::after {
    height: 0px;
  }
}

.el-table {
  margin: 0;
  padding: 0;
}
.page {
  margin-top: 30px;
}
</style>